package com.hanxiaozhang.example.listener.mgsconsumer;

import com.hanxiaozhang.constant.RocketConstant;
import com.hanxiaozhang.example.entity.RocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultLitePullConsumer;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈自定义拉去消息监听器〉
 * CommandLineRunner：Springboot启动后，就开始运行
 *
 * @author hanxinghua
 * @create 2022/10/3
 * @since 1.0.0
 */
@Slf4j
@Component
public class No6PullMgsRocketMqTemplate implements CommandLineRunner {

    public static volatile boolean running = true;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void run(String... args) throws Exception {

        DefaultLitePullConsumer litePullConsumer = new DefaultLitePullConsumer(RocketConstant.LITE_PULL_TEMPLATE_CONSUMER_GROUP);
        litePullConsumer.subscribe(RocketConstant.LITE_PULL_TEMPLATE_TOPIC, "*");
        litePullConsumer.start();
        rocketMQTemplate.setConsumer(litePullConsumer);

        while (running) {
            // 获取全部的消息信息
            List<RocketMessage> messages = rocketMQTemplate.receive(RocketMessage.class);
            if (messages.size() > 0) {
                log.info("消息大小：{}", messages.size());
                for (int i = 0; i < messages.size(); i++) {
                    log.info("{}收到消息：{}", this.getClass().getSimpleName(), messages.get(i));
                }
            }
        }
    }
}